<!DOCTYPE html>
<html lang="zh-CN">
<!--浏览器搞笑标题-->
<script type="text/javascript" src="/js/FunnyTitle.js"></script>






<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/binblog/img/binblog.ico">
  <link rel="icon" type="image/png" href="/binblog/img/binblog.ico">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="leo-bin">
  <meta name="keywords" content="">
  <title>仿照Redisson实现一个简易版分布式锁 - 阿斌的个人博客</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/binblog/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/dracula.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">


<link  rel="stylesheet" href="/binblog/css/main.css" />

<!-- 自定义样式保持在最底部 -->


<meta name="generator" content="Hexo 4.2.1"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/binblog/">&nbsp;<strong>Abin的Blog</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('/binblog/img/6.webp') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2020-07-07 18:41">
      2020年7月7日 晚上
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      3.3k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      43
       分钟
    </span>
  

  
  
    
      <!-- LeanCloud 统计文章PV -->
      <span id="leancloud-post-views-container" class="post-meta" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="leancloud-post-views"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
              <p class="note note-info">
                
                  本文最后更新于：2020年7月7日 晚上
                
              </p>
            
            <article class="markdown-body">
              <h1>仿照Redisson实现一个简易版分布式锁</h1>
<h2 id="前言"><a class="header-anchor" href="#前言"></a>前言</h2>
<div class="hljs"><pre><code class="hljs xml">首先Redisson是一个使用Java实现的redis客户端工具。
但是我们之前的项目中已经使用了Jedis和RedisTemplate作为redis客户端了，感觉在使用Redisson的话就有点重复了。
一个稳定可用的分布式锁需要解决因为网络或者其他原因导致的断线重连，过期续锁的功能，而Jedis和RedisTemplate都无法提供支持。
所以这里打算自己写一个基于Jedis的分布式锁。</code></pre></div>
<p><strong>既然是仿照，那就非常有必要撸一把Redisson的源码了</strong></p>
<p><strong>所以这里我们从源码开始一步一步的解读Redisson是如何实现分布式锁的</strong></p>
<p><strong>先看一个整体的流程图</strong></p>
<p><img src="https://bins-pic.oss-cn-shanghai.aliyuncs.com/mypic/redisson%E6%89%A7%E8%A1%8C%E6%B5%81%E7%A8%8B%E5%9B%BE.jpg" srcset="/binblog/img/loading.gif" alt=""></p>
<h2 id="加锁"><a class="header-anchor" href="#加锁"></a>加锁</h2>
<p><img src="https://bins-pic.oss-cn-shanghai.aliyuncs.com/mypic/Redisson%E5%8A%A0%E9%94%81%E6%B5%81%E7%A8%8B%E5%9B%BE.png" srcset="/binblog/img/loading.gif" alt=""></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-number">1</span>.每次加锁时都会向redis服务器发送一段lua脚本，这段脚本的功能就是给指定的某个key设置一个随机值，并且设置过期时间。
<span class="hljs-number">2</span>.脚本首先会判断key是否已经存在，如果存在说明有其他线程正在执行任务，那就原地阻塞或者不等待直接返回<span class="hljs-keyword">false</span>，表示获取锁失败。
<span class="hljs-number">3</span>.如果不存在，那就直接set值。并设置key的过期时间。</code></pre></div>
<p><strong>脚本如下：</strong></p>
<div class="hljs"><pre><code class="hljs java">这段lua脚本可以分为三个部分去理解：

第一部分：
第一个<span class="hljs-keyword">if</span> ... then ... end，大概就是判断key是否存在
不存在才能接着往下走，否则就走下一个<span class="hljs-keyword">if</span>逻辑了。

第二部分：
就是第二个<span class="hljs-keyword">if</span> ... then ... end，这里就是判断是否进入重入的逻辑
如果第二个参数相同的话，说明是同一个线程，那就会将原来的key中的值+<span class="hljs-number">1</span>。

第三部分：
就是最后的<span class="hljs-keyword">return</span>语句了，这里就是获取当前key的剩余过期时间并将之返回。

ARGV[<span class="hljs-number">1</span>]=key的过期时间
ARGV[<span class="hljs-number">2</span>]=key的值
pexpire和expire作用相同，不过时间单位默认是毫秒，后者则是秒
pttl：获取key的过期时间</code></pre></div>
<div class="hljs"><pre><code class="hljs java">String LOCK_LUA = <span class="hljs-string">"if (redis.call('exists', KEYS[1]) == 0) then "</span> +
        <span class="hljs-string">"redis.call('hset', KEYS[1], ARGV[2], 1); "</span> +
        <span class="hljs-string">"redis.call('pexpire', KEYS[1], ARGV[1]); "</span> +
        <span class="hljs-string">"return nil; "</span> +
        <span class="hljs-string">"end; "</span> +
        <span class="hljs-string">"if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then "</span> +
        <span class="hljs-string">"redis.call('hincrby', KEYS[1], ARGV[2], 1); "</span> +
        <span class="hljs-string">"redis.call('pexpire', KEYS[1], ARGV[1]); "</span> +
        <span class="hljs-string">"return nil; "</span> +
        <span class="hljs-string">"end; "</span> +
        <span class="hljs-string">"return redis.call('pttl', KEYS[1]);"</span>;</code></pre></div>
<p><strong>执行完之后，现在redis中key的结构可以理解成这样子：</strong></p>
<div class="hljs"><pre><code class="hljs java">mylock：&#123;
“i554d4fd5f4d54f5d4f54544”:&#123;<span class="hljs-number">1</span>&#125;
&#125;</code></pre></div>
<p>相当于：</p>
<p><strong>&lt;key,&lt;key,value&gt;&gt;</strong></p>
<p>其中第一个key指的是分布式锁的key</p>
<p>第二个key指的是分布式锁的唯一id(每次获取锁的时候动态生成的，可以理解为线程id)</p>
<p>最后一个value就是当前这个线程所持有锁的重入次数</p>
<h2 id="可重入式机制"><a class="header-anchor" href="#可重入式机制"></a>可重入式机制</h2>
<p>这里的可重入式机制就是依赖于上面说过的LUA脚本的第二段lf逻辑：</p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-string">"if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then "</span> +
            <span class="hljs-string">"redis.call('hincrby', KEYS[1], ARGV[2], 1); "</span> +
            <span class="hljs-string">"redis.call('pexpire', KEYS[1], ARGV[1]); "</span> +
            <span class="hljs-string">"return nil; "</span> +
            <span class="hljs-string">"end; "</span> +</code></pre></div>
<h2 id="释放锁"><a class="header-anchor" href="#释放锁"></a>释放锁</h2>
<p>既然之前一个分布式锁有了重入机制，原理就是不断的对value值+1</p>
<p>那么这里只要依次执行-1操作就行了，直到判断出这个时候的counter&lt;=0说明可以放心的删掉这个锁了</p>
<p>同样的，我们照样可以使用一段lua脚本来实现：</p>
<p><strong>解释：</strong></p>
<p>第一个if逻辑是判断key是否存在，如果不存在就直接返回1表示释放锁成功。</p>
<p>第二个if逻辑是判断key中的value是否和当前线程id一致，如果不一致说明不能释放锁，返回空。</p>
<p>第三个if逻辑中设置了一个本地counter变量，用来记录锁的重入次数，每次都执行counter-1的操作。</p>
<p>只有当counter&lt;=0时才能删除这个key，并返回1表示释放锁成功。</p>
<p>如果counter&gt;0则重新设置过期时间，让其他线程来释放这个锁，并返回0，表示释放锁失败</p>
<p><img src="https://bins-pic.oss-cn-shanghai.aliyuncs.com/mypic/Redisson%E8%A7%A3%E9%94%81%E6%B5%81%E7%A8%8B%E5%9B%BE.png" srcset="/binblog/img/loading.gif" alt=""></p>
<div class="hljs"><pre><code class="hljs java">String UNLOCK_LUA = <span class="hljs-string">"if (redis.call('exists', KEYS[1]) == 0) then "</span> +
        <span class="hljs-string">"return 1; "</span> +
        <span class="hljs-string">"end;"</span> +
        <span class="hljs-string">"if (redis.call('hexists', KEYS[1], ARGV[1]) == 0) then "</span> +
        <span class="hljs-string">"return nil;"</span> +
        <span class="hljs-string">"end; "</span> +
        <span class="hljs-string">"local counter = redis.call('hincrby', KEYS[1], ARGV[1], -1); "</span> +
        <span class="hljs-string">"if (counter &gt; 0) then "</span> +
        <span class="hljs-string">"redis.call('pexpire', KEYS[1], ARGV[2]); "</span> +
        <span class="hljs-string">"return 0; "</span> +
        <span class="hljs-string">"else "</span> +
        <span class="hljs-string">"redis.call('del', KEYS[1]); "</span> +
        <span class="hljs-string">"return 1; "</span> +
        <span class="hljs-string">"end; "</span> +
        <span class="hljs-string">"return nil;"</span>;</code></pre></div>
<h2 id="过期续锁（看门狗机制）"><a class="header-anchor" href="#过期续锁（看门狗机制）"></a>过期续锁（看门狗机制）</h2>
<p>之所以有看门狗机制的出现，就是为了应对锁过期了，但是业务还未执行完毕。</p>
<p>这个时候就可以增加一个监听器，每隔一定的时间去查看现在的key的过期时间是否到了。</p>
<p>如果没到，那就自动更新锁的过期时间。</p>
<p>同样的，我们还是可以使用LUA脚本进行逻辑的封装：</p>
<div class="hljs"><pre><code class="hljs java">String KEEP_LOCK_LUA = <span class="hljs-string">"if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then "</span> +
        <span class="hljs-string">"redis.call('pexpire', KEYS[1], ARGV[1]); "</span> +
        <span class="hljs-string">"return 1; "</span> +
        <span class="hljs-string">"end; "</span> +
        <span class="hljs-string">"return 0;"</span>;</code></pre></div>
<h2 id="完整的实现"><a class="header-anchor" href="#完整的实现"></a>完整的实现</h2>
<p><strong>先将上面提到的LUA脚本进行封装：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">LuaScript</span> </span>&#123;
    Long SUCCESS = <span class="hljs-number">1L</span>;

    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 获取锁</span>
<span class="hljs-comment">     */</span>
    String LOCK_LUA = <span class="hljs-string">"if (redis.call('exists', KEYS[1]) == 0) then "</span> +
            <span class="hljs-string">"redis.call('hset', KEYS[1], ARGV[2], 1); "</span> +
            <span class="hljs-string">"redis.call('pexpire', KEYS[1], ARGV[1]); "</span> +
            <span class="hljs-string">"return nil; "</span> +
            <span class="hljs-string">"end; "</span> +
            <span class="hljs-string">"if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then "</span> +
            <span class="hljs-string">"redis.call('hincrby', KEYS[1], ARGV[2], 1); "</span> +
            <span class="hljs-string">"redis.call('pexpire', KEYS[1], ARGV[1]); "</span> +
            <span class="hljs-string">"return nil; "</span> +
            <span class="hljs-string">"end; "</span> +
            <span class="hljs-string">"return redis.call('pttl', KEYS[1]);"</span>;

    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 续锁，重新给key续上过期时间</span>
<span class="hljs-comment">     */</span>
    String KEEP_LOCK_LUA = <span class="hljs-string">"if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then "</span> +
            <span class="hljs-string">"redis.call('pexpire', KEYS[1], ARGV[1]); "</span> +
            <span class="hljs-string">"return 1; "</span> +
            <span class="hljs-string">"end; "</span> +
            <span class="hljs-string">"return 0;"</span>;

    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 释放锁</span>
<span class="hljs-comment">     */</span>
    String UNLOCK_LUA = <span class="hljs-string">"if (redis.call('exists', KEYS[1]) == 0) then "</span> +
            <span class="hljs-string">"return 1; "</span> +
            <span class="hljs-string">"end;"</span> +
            <span class="hljs-string">"if (redis.call('hexists', KEYS[1], ARGV[1]) == 0) then "</span> +
            <span class="hljs-string">"return nil;"</span> +
            <span class="hljs-string">"end; "</span> +
            <span class="hljs-string">"local counter = redis.call('hincrby', KEYS[1], ARGV[1], -1); "</span> +
            <span class="hljs-string">"if (counter &gt; 0) then "</span> +
            <span class="hljs-string">"redis.call('pexpire', KEYS[1], ARGV[2]); "</span> +
            <span class="hljs-string">"return 0; "</span> +
            <span class="hljs-string">"else "</span> +
            <span class="hljs-string">"redis.call('del', KEYS[1]); "</span> +
            <span class="hljs-string">"return 1; "</span> +
            <span class="hljs-string">"end; "</span> +
            <span class="hljs-string">"return nil;"</span>;
&#125;</code></pre></div>
<h3 id="1）加锁"><a class="header-anchor" href="#1）加锁"></a>1）加锁</h3>
<p>加锁的逻辑其实很简单，大部分其实已经封装在了LUA脚本中了</p>
<p>这边只要判断执行结果并启动看门狗任务就行</p>
<p><strong>关键代码：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">tryLock</span><span class="hljs-params">(<span class="hljs-keyword">long</span> leaseTime)</span> </span>&#123;
    RedisScript&lt;Long&gt; redisScript = <span class="hljs-keyword">new</span> DefaultRedisScript&lt;&gt;(LOCK_LUA, Long<span class="hljs-class">.<span class="hljs-keyword">class</span>)</span>;
    <span class="hljs-comment">//锁过期的剩余时间</span>
    Long ttl = (Long) redisTemplate.execute(redisScript, Collections.singletonList(lockName), leaseTime, id);
    <span class="hljs-comment">//剩余时间为null说明拿到锁了</span>
    <span class="hljs-keyword">if</span> (ttl == <span class="hljs-keyword">null</span>) &#123;
        <span class="hljs-comment">//开启看门狗</span>
        startWatchDogTask(leaseTime);
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
    &#125;
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
&#125;</code></pre></div>
<h3 id="2）看门狗机制"><a class="header-anchor" href="#2）看门狗机制"></a>2）看门狗机制</h3>
<p>这里不同于源码的实现，为了图简单，我这里是配置了一个全局线程池</p>
<p>并异步的去开启一个看门狗线程，同时启动一个定时器Timer(jdk自带的)</p>
<p>每隔一段时间就去查询key的过期时间，如果还没过期的话，那就执行续锁的逻辑</p>
<p>这个续锁的逻辑同样封装在了LUA脚本中了</p>
<p>除此之外，这里还参照了源码的一个细节</p>
<p>就是为了实现重入式锁的功能，如果每次执行拿锁的动作就要开启一个看门狗任务</p>
<p>理论其实上一个线程只要一个看门狗线程就行了</p>
<p>那如果还是一个线程但是开启了多个看门狗任务怎么办？</p>
<p>简单！我们可以用一个Map来存所有的看门狗任务！</p>
<p>每次开启看门狗任务之前只需要通过Contains方法判断任务是否存在过就行</p>
<p>考虑到多线程的环境下，这里使用ConcurrentHashMap来存：</p>
<p><strong>&lt;key就是锁的名字，value就是一把锁对应的看门狗任务&gt;</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-comment">/**</span>
<span class="hljs-comment"> * 看门狗定时任务集合</span>
<span class="hljs-comment"> */</span>
<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> ConcurrentHashMap&lt;String, WatchDogTask&gt; WATCH_DOGS = <span class="hljs-keyword">new</span> ConcurrentHashMap&lt;&gt;(<span class="hljs-number">16</span>);</code></pre></div>
<p><strong>关键代码：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-comment">/**</span>
<span class="hljs-comment"> * 看门狗任务，继续给key设置过期时间，相当于续锁</span>
<span class="hljs-comment"> */</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">startWatchDogTask</span><span class="hljs-params">(<span class="hljs-keyword">long</span> timeout)</span> </span>&#123;
    <span class="hljs-comment">//说明定时任务已经存在直接返回就行</span>
    <span class="hljs-keyword">if</span> (WATCH_DOGS.containsKey(lockName)) &#123;
        <span class="hljs-keyword">return</span>;
    &#125;
    <span class="hljs-comment">//通过全局线程池，异步开启一个新的看门狗线程去监听锁的状态</span>
    WatchDogTask task = <span class="hljs-keyword">new</span> WatchDogTask(redisTemplate, timeout, lockName, id);
    ThreadPoolUtil.getExecutor().execute(task);

    <span class="hljs-comment">//放入看门狗集合中，如果put失败就取消任务</span>
    <span class="hljs-keyword">if</span> (WATCH_DOGS.putIfAbsent(lockName, task) != <span class="hljs-keyword">null</span>) &#123;
        task.cancelTask();
    &#125;
&#125;</code></pre></div>
<p><strong>这里给出WatchDogTask的源码：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-meta">@Slf</span>4j
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">WatchDogTask</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span> </span>&#123;
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 看门狗任务默认调度时间</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">long</span> defaultTimeout = <span class="hljs-number">30</span> * <span class="hljs-number">1000</span>;
    <span class="hljs-keyword">private</span> RedisTemplate redisTemplate;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">long</span> timeout;
    <span class="hljs-keyword">private</span> String lockName;
    <span class="hljs-keyword">private</span> String id;
    <span class="hljs-keyword">private</span> Timer timer;
    <span class="hljs-keyword">private</span> TimerTask task = <span class="hljs-keyword">new</span> TimerTask() &#123;
        <span class="hljs-meta">@Override</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>&#123;
            RedisScript&lt;Long&gt; redisScript = <span class="hljs-keyword">new</span> DefaultRedisScript&lt;&gt;(KEEP_LOCK_LUA, Long<span class="hljs-class">.<span class="hljs-keyword">class</span>)</span>;
            Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockName), timeout, id);

            <span class="hljs-comment">//续锁成功</span>
            <span class="hljs-keyword">if</span> (SUCCESS.equals(result)) &#123;
                log.info(<span class="hljs-string">"看门狗线程：&#123;&#125;，续锁成功！"</span>, Thread.currentThread().getName());
            &#125; <span class="hljs-keyword">else</span> &#123;
                log.error(<span class="hljs-string">"无法更新锁的过期时间！"</span>);
            &#125;
        &#125;
    &#125;;
    
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">WatchDogTask</span><span class="hljs-params">(RedisTemplate redisTemplate, <span class="hljs-keyword">long</span> timeout, String lockName, String id)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.redisTemplate = redisTemplate;
        <span class="hljs-keyword">this</span>.timeout = timeout;
        <span class="hljs-keyword">this</span>.lockName = lockName;
        <span class="hljs-keyword">this</span>.id = id;
    &#125;

    
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>&#123;
        watch();
    &#125;


    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 开启看门狗任务</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">watch</span><span class="hljs-params">()</span> </span>&#123;
        log.info(<span class="hljs-string">"看门狗线程：&#123;&#125;已经启动"</span>, Thread.currentThread().getName());
        timer = <span class="hljs-keyword">new</span> Timer();
        <span class="hljs-comment">//延迟执行</span>
        <span class="hljs-keyword">long</span> delay = timeout / <span class="hljs-number">3</span>;
        <span class="hljs-comment">//间隔执行</span>
        <span class="hljs-keyword">long</span> intervalTime = timeout / <span class="hljs-number">3</span>;

        <span class="hljs-comment">//提交任务</span>
        timer.scheduleAtFixedRate(task, delay, intervalTime);
    &#125;


    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 取消定时任务</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">cancelTask</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">if</span> (timer != <span class="hljs-keyword">null</span>) &#123;
            timer.cancel();
            log.info(<span class="hljs-string">"看门狗线程：&#123;&#125;的任务已经结束！"</span>, Thread.currentThread().getName());
        &#125;
    &#125;
&#125;</code></pre></div>
<h3 id="3）释放锁"><a class="header-anchor" href="#3）释放锁"></a>3）释放锁</h3>
<p>释放锁没有什么重要的地方需要讲解了，直接看代码就行</p>
<p>无非就是执行脚本，判断执行结果就行了</p>
<p><strong>关键代码：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">unLock</span><span class="hljs-params">()</span> </span>&#123;
    RedisScript&lt;Long&gt; redisScript = <span class="hljs-keyword">new</span> DefaultRedisScript&lt;&gt;(UNLOCK_LUA, Long<span class="hljs-class">.<span class="hljs-keyword">class</span>)</span>;
    Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockName), id, internalLockLeaseTime);
    <span class="hljs-comment">//当前没有锁可以释放</span>
    <span class="hljs-keyword">if</span> (result == <span class="hljs-keyword">null</span>) &#123;
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalMonitorStateException(<span class="hljs-string">"attempt to unlock lock, not locked by current thread by node id: "</span>+ id + <span class="hljs-string">" thread-id: "</span> + Thread.currentThread().getId());
    &#125;
    <span class="hljs-comment">//释放锁成功，取消看门狗的定时任务</span>
    <span class="hljs-keyword">if</span> (result.equals(SUCCESS)) &#123;
        cancelWatchDogTask();
        log.info(<span class="hljs-string">"线程：&#123;&#125;，锁成功被释放了！"</span>, Thread.currentThread().getName());
    &#125;
&#125;</code></pre></div>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-comment">/**</span>
<span class="hljs-comment"> * 锁已经成功被释放了，取消看门狗任务</span>
<span class="hljs-comment"> */</span>
<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">cancelWatchDogTask</span><span class="hljs-params">()</span> </span>&#123;
    WatchDogTask task = WATCH_DOGS.remove(lockName);
    <span class="hljs-comment">//删除失败手动取消任务</span>
    <span class="hljs-keyword">if</span> (task != <span class="hljs-keyword">null</span>) &#123;
        task.cancelTask();
    &#125;
&#125;</code></pre></div>
<h2 id="测试"><a class="header-anchor" href="#测试"></a>测试</h2>
<p>为了测试方便，我们可以将分布式锁的功能进行封装</p>
<p><strong>值得一提的是我们并没有在获取锁失败的时候不断的进行重试，二是直接将失败的结果返回</strong></p>
<p><strong>之所以这么做的愿意就是这里通过返回的结果进行进行自定义的重试机制</strong></p>
<p><strong>比如说这里设置了一旦失败了，最多可以重试30次，超过30次就直接返回获取锁失败</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-meta">@Slf</span>4j
<span class="hljs-meta">@Service</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RedisService</span> </span>&#123;
    <span class="hljs-meta">@Resource</span>
    <span class="hljs-keyword">private</span> EasyRedissonClient easyRedissonClient;
    <span class="hljs-comment">//最大重试次数</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> MAX_RETRY_COUNT = <span class="hljs-number">30</span>;
    <span class="hljs-comment">//使用ThreadLocal来记录每一个线程的尝试次数</span>
    ThreadLocal&lt;Integer&gt; count = <span class="hljs-keyword">new</span> ThreadLocal&lt;&gt;();


    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">access</span><span class="hljs-params">(String key, <span class="hljs-keyword">long</span> timeout)</span> </span>&#123;
        EasyRedissonLock easyLock = easyRedissonClient.getLock(key);
        count.set(<span class="hljs-number">0</span>);
        <span class="hljs-keyword">try</span> &#123;
            <span class="hljs-comment">//原地自旋去拿锁</span>
            <span class="hljs-keyword">while</span> (!easyLock.tryLock(timeout)) &#123;
                count.set(count.get() + <span class="hljs-number">1</span>);
                log.info(<span class="hljs-string">"线程：&#123;&#125;抢占锁失败！再次尝试获取锁！重试次数：&#123;&#125;"</span>, Thread.currentThread().getName(), count.get());
                <span class="hljs-comment">//自旋超过30次则自动失败</span>
                <span class="hljs-keyword">if</span> (count.get() == MAX_RETRY_COUNT) &#123;
                    log.error(<span class="hljs-string">"重试次数超过了最大限制：&#123;&#125;"</span>, MAX_RETRY_COUNT);
                    <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
                &#125;
            &#125;
            log.info(<span class="hljs-string">"线程：&#123;&#125;，成功拿到分布式锁啦！"</span>, Thread.currentThread().getName());
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
        &#125; <span class="hljs-keyword">catch</span> (Exception e) &#123;
            e.printStackTrace();
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
        &#125; <span class="hljs-keyword">finally</span> &#123;
            easyLock.unLock();
        &#125;
    &#125;
&#125;</code></pre></div>
<h3 id="1）测试代码"><a class="header-anchor" href="#1）测试代码"></a>1）测试代码</h3>
<p><strong>这里用的SpringBoot中自带的单元测试</strong></p>
<p>同时开启两个线程去竞争锁</p>
<p>每抢到一次锁就记录下访问次数</p>
<p>每个线程执行50次，所以最后的记录结果一定是100</p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-meta">@Slf</span>4j
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TestResyRedissonTest</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">EasyRedissonApplicationTests</span> </span>&#123;
    <span class="hljs-meta">@Resource</span>
    <span class="hljs-keyword">private</span> RedisService redisService;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> AtomicInteger apiAccessCount = <span class="hljs-keyword">new</span> AtomicInteger(<span class="hljs-number">0</span>);

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testEasyLock</span><span class="hljs-params">()</span> </span>&#123;
        String redisLockKey = <span class="hljs-string">"redis.lock.key"</span>;
        <span class="hljs-keyword">long</span> timeout = <span class="hljs-number">5000L</span>;

        <span class="hljs-comment">//模拟线程一</span>
        <span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> Runnable() &#123;
            <span class="hljs-meta">@Override</span>
            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>&#123;
                <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">50</span>; i++) &#123;
                    <span class="hljs-keyword">try</span> &#123;
                        <span class="hljs-comment">//模拟网络延时</span>
                        Thread.sleep(<span class="hljs-number">10L</span>);
                    &#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;
                        e.printStackTrace();
                    &#125;
                    <span class="hljs-keyword">if</span> (redisService.access(redisLockKey, timeout)) &#123;
                        log.info(<span class="hljs-string">"接口访问次数记录成功！次数+1,现在api被访问了：&#123;&#125;次"</span>, apiAccessCount.incrementAndGet());
                    &#125; <span class="hljs-keyword">else</span> &#123;
                        log.info(<span class="hljs-string">"接口访问次数记录失败！"</span>);
                    &#125;
                &#125;
                log.info(<span class="hljs-string">"线程&#123;&#125;结束了，此时的api访问次数是:&#123;&#125;"</span>, Thread.currentThread().getName(), apiAccessCount.get());
            &#125;
        &#125;).start();

        <span class="hljs-comment">//模拟线程二</span>
        <span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> Runnable() &#123;
            <span class="hljs-meta">@Override</span>
            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>&#123;
                <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">50</span>; i++) &#123;
                    <span class="hljs-keyword">try</span> &#123;
                        <span class="hljs-comment">//模拟网络延时</span>
                        Thread.sleep(<span class="hljs-number">10L</span>);
                    &#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;
                        e.printStackTrace();
                    &#125;
                    <span class="hljs-keyword">if</span> (redisService.access(redisLockKey, timeout)) &#123;
                        log.info(<span class="hljs-string">"接口访问次数记录成功！次数+1,现在api被访问了：&#123;&#125;次"</span>, apiAccessCount.incrementAndGet());
                    &#125; <span class="hljs-keyword">else</span> &#123;
                        log.info(<span class="hljs-string">"接口访问次数记录失败！"</span>);
                    &#125;
                &#125;
                log.info(<span class="hljs-string">"线程&#123;&#125;结束了，此时的api访问次数是:&#123;&#125;"</span>, Thread.currentThread().getName(), apiAccessCount.get());
            &#125;
        &#125;).start();
        
        <span class="hljs-comment">//主线程必须处于运行状态</span>
        <span class="hljs-keyword">for</span> (; ; ) &#123;

        &#125;
    &#125;
&#125;</code></pre></div>
<h3 id="2）测试结果"><a class="header-anchor" href="#2）测试结果"></a>2）测试结果</h3>
<img src="https://bins-pic.oss-cn-shanghai.aliyuncs.com/mypic/redis实现分布式锁测试结果.png" srcset="/binblog/img/loading.gif" style="zoom:200%;" />
<p><strong>最后的结果：</strong></p>
<img src="https://bins-pic.oss-cn-shanghai.aliyuncs.com/mypic/redis实现分布式锁测试结果2.png" srcset="/binblog/img/loading.gif" style="zoom:200%;" />
<h2 id="最后"><a class="header-anchor" href="#最后"></a>最后</h2>
<p>当然，这里实现的很简陋，还有很多功能都没有实现。</p>
<p>比如说如何应对网络异常的问题还有主从模式下出现的同一把锁被多个节点拿到的问题等等。</p>
<p><strong>所有的代码都放在了github上，感兴趣可以pull         <a href="https://github.com/leo-bin/easy-redisson.git" target="_blank" rel="noopener">https://github.com/leo-bin/easy-redisson.git</a></strong></p>
<p><strong>真没想到秋招提前批这么快就开始了，加油吧！</strong></p>
<h2 id="参考"><a class="header-anchor" href="#参考"></a>参考</h2>
<p>1.<a href="https://mp.weixin.qq.com/s/y_Uw3P2Ll7wvk_j5Fdlusw" target="_blank" rel="noopener">https://mp.weixin.qq.com/s/y_Uw3P2Ll7wvk_j5Fdlusw</a></p>
<p>2.<a href="http://ifeve.com/%E6%85%A2%E8%B0%88-redis-%E5%AE%9E%E7%8E%B0%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81-%E4%BB%A5%E5%8F%8A-redisson-%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90/" target="_blank" rel="noopener">http://ifeve.com/%E6%85%A2%E8%B0%88-redis-%E5%AE%9E%E7%8E%B0%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81-%E4%BB%A5%E5%8F%8A-redisson-%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90/</a></p>
<p>3.<a href="https://blog.csdn.net/ice24for/article/details/86177152" target="_blank" rel="noopener">https://blog.csdn.net/ice24for/article/details/86177152</a></p>
<p>4.<a href="https://juejin.im/post/5e6727e16fb9a07cc845b9ba" target="_blank" rel="noopener">https://juejin.im/post/5e6727e16fb9a07cc845b9ba</a></p>

            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/binblog/categories/%E6%A1%86%E6%9E%B6/">框架</a>
                    
                  </div>
                
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/binblog/2020/07/13/%E5%A6%82%E4%BD%95%E6%89%93%E9%80%A0%E6%B0%B8%E4%B9%85%E5%B8%A6%E5%9F%9F%E5%90%8D%E4%B8%AA%E4%BA%BA%E4%B8%93%E5%B1%9E%E5%8D%9A%E5%AE%A2/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">如何打造带域名的永久个人专属博客</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/binblog/2020/06/01/%E6%88%91%E7%88%B6%E6%AF%8D%E4%B9%8B%E9%97%B4%E7%9A%84%E7%88%B1%E6%83%85/">
                        <span class="hidden-mobile">我父母之间的爱情</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
              <!-- Comments -->
              <div class="comments" id="comments">
                
                
  <div id="vcomments"></div>
  <script defer src="https://cdn.staticfile.org/valine/1.4.14/Valine.min.js" ></script>

  <script type="text/javascript">
    var oldLoadVa = window.onload;
    window.onload = function () {
      oldLoadVa && oldLoadVa();

      new Valine({
        el: "#vcomments",
        app_id: "vsanVmkaurLHyq2Xey9odo5V-gzGzoHsz",
        app_key: "v2hMMe4Mzz3mqpy9jwd7qx8B",
        placeholder: "说点什么吧！",
        path: window.location.pathname,
        avatar: "retro",
        meta: ["nick","mail","link"],
        pageSize: "10",
        lang: "zh-CN",
        highlight: true,
        recordIP: false,
        serverURLs: "",
      });
    };
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://valine.js.org" target="_blank" rel="nofollow noopener noopener">comments
      powered by Valine.</a></noscript>


              </div>
            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    
  <div class="statistics">
    
    

    
      
        <!-- LeanCloud 统计PV -->
        <span id="leancloud-site-pv-container" style="display: none">
            总访问量 
            <span id="leancloud-site-pv"></span>
             次
          </span>
      
      
        <!-- LeanCloud 统计UV -->
        <span id="leancloud-site-uv-container" style="display: none">
            总访客数 
            <span id="leancloud-site-uv"></span>
             人
          </span>
      

    
  </div>


    
  <!-- 备案信息 -->
  <div class="beian">
    <a href="http://beian.miit.gov.cn/" target="_blank"
       rel="nofollow noopener">京ICP证123456号</a>
    
      <a
        href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=12345678"
        rel="nofollow noopener"
        class="beian-police"
        target="_blank"
      >
        <span class="beian-police-sep">&nbsp;|&nbsp;</span>
        
          <img src="/binblog/img/police_beian.png" srcset="/binblog/img/loading.gif" alt="police-icon" />
        
        <span>京公网安备12345678号</span>
      </a>
     
  </div>


    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/binblog/js/debouncer.js" ></script>
<script  src="/binblog/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/binblog/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/binblog/js/clipboard-use.js" ></script>



  <script defer>
  (function () {
    // 查询存储的记录
    function getRecord(Counter, target) {
      return new Promise(function (resolve, reject) {
        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({target})))
          .then(resp => resp.json())
          .then(({results, code, error}) => {
            if (code === 401) {
              throw error;
            }
            if (results && results.length > 0) {
              var record = results[0];
              resolve(record);
            } else {
              Counter('post', '/classes/Counter', {target, time: 0})
                .then(resp => resp.json())
                .then((record, error) => {
                  if (error) {
                    throw error;
                  }
                  resolve(record);
                }).catch(error => {
                console.error('Failed to create', error);
                reject(error);
              });
            }
          }).catch((error) => {
          console.error('LeanCloud Counter Error:', error);
          reject(error);
        });
      })
    }

    // 发起自增请求
    function increment(Counter, incrArr) {
      return new Promise(function (resolve, reject) {
        Counter('post', '/batch', {
          "requests": incrArr
        }).then((res) => {
          res = res.json();
          if (res.error) {
            throw res.error;
          }
          resolve(res);
        }).catch((error) => {
          console.error('Failed to save visitor count', error);
          reject(error);
        });
      });
    }

    // 构建自增请求体
    function buildIncrement(objectId) {
      return {
        "method": "PUT",
        "path": `/1.1/classes/Counter/${ objectId }`,
        "body": {
          "time": {
            '__op': 'Increment',
            'amount': 1
          }
        }
      }
    }

    // 校验是否为有效的 UV
    function validUV() {
      var key = 'LeanCloud_UV_Flag';
      var flag = localStorage.getItem(key);
      if (flag) {
        // 距离标记小于 24 小时则不计为 UV
        if (new Date().getTime() - parseInt(flag) <= 86400000) {
          return false;
        }
      }
      localStorage.setItem(key, new Date().getTime().toString());
      return true;
    }

    function addCount(Counter) {
      var enableIncr = 'true' === 'true' && window.location.hostname !== 'localhost';
      var getterArr = [];
      var incrArr = [];

      // 请求 PV 并自增
      var pvCtn = document.querySelector('#leancloud-site-pv-container');
      if (pvCtn || enableIncr) {
        var pvGetter = getRecord(Counter, 'site-pv').then((record) => {
          incrArr.push(buildIncrement(record.objectId))
          var ele = document.querySelector('#leancloud-site-pv');
          if (ele) {
            ele.innerText = record.time + 1;
            if (pvCtn) {
              pvCtn.style.display = 'inline';
            }
          }
        });
        getterArr.push(pvGetter);
      }

      // 请求 UV 并自增
      var uvCtn = document.querySelector('#leancloud-site-uv-container');
      if (uvCtn || enableIncr) {
        var uvGetter = getRecord(Counter, 'site-uv').then((record) => {
          var vuv = validUV();
          vuv && incrArr.push(buildIncrement(record.objectId))
          var ele = document.querySelector('#leancloud-site-uv');
          if (ele) {
            ele.innerText = record.time + (vuv ? 1 : 0);
            if (uvCtn) {
              uvCtn.style.display = 'inline';
            }
          }
        });
        getterArr.push(uvGetter);
      }

      // 如果是文章，请求文章的浏览数，并自增
      if ('true' === 'true') {
        var viewCtn = document.querySelector('#leancloud-post-views-container');
        if (viewCtn || enableIncr) {
          var target = decodeURI('/binblog/2020/07/07/%E5%A6%82%E4%BD%95%E4%BB%BF%E7%85%A7Redisson%E5%AE%9E%E7%8E%B0%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81/');
          var viewGetter = getRecord(Counter, target).then((record) => {
            incrArr.push(buildIncrement(record.objectId))
            if (viewCtn) {
              var ele = document.querySelector('#leancloud-post-views');
              if (ele) {
                ele.innerText = (record.time || 0) + 1;
                viewCtn.style.display = 'inline';
              }
            }
          });
          getterArr.push(viewGetter);
        }
      }

      // 如果启动计数自增，批量发起自增请求
      if (enableIncr) {
        Promise.all(getterArr).then(() => {
          incrArr.length > 0 && increment(Counter, incrArr);
        })
      }
    }

    var app_id = 'vsanVmkaurLHyq2Xey9odo5V-gzGzoHsz'
    var app_key = 'v2hMMe4Mzz3mqpy9jwd7qx8B'
    var server_url = ''

    function fetchData(api_server) {
      var Counter = (method, url, data) => {
        return fetch(`${ api_server }/1.1${ url }`, {
          method,
          headers: {
            'X-LC-Id': app_id,
            'X-LC-Key': app_key,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
      };

      addCount(Counter);
    }

    var api_server = app_id.slice(-9) !== '-MdYXbMMI' ? server_url : `https://${ app_id.slice(0, 8).toLowerCase() }.api.lncldglobal.com`;

    if (api_server) {
      fetchData(api_server);
    } else {
      fetch('https://app-router.leancloud.cn/2/route?appId=' + app_id)
        .then(resp => resp.json())
        .then(({api_server}) => {
          fetchData('https://' + api_server);
        });
    }
  })();
</script>






  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "仿照Redisson实现一个简易版分布式锁&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/binblog/js/local-search.js" ></script>
  <script>
    var path = "/binblog/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>





  

  
    <!-- MathJax -->
    <script>
      MathJax = {
        tex: {
          inlineMath: [['$', '$'], ['\\(', '\\)']]
        },
        options: {
          renderActions: {
            findScript: [10, doc => {
              document.querySelectorAll('script[type^="math/tex"]').forEach(node => {
                const display = !!node.type.match(/; *mode=display/);
                const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display);
                const text = document.createTextNode('');
                node.parentNode.replaceChild(text, node);
                math.start = { node: text, delim: '', n: 0 };
                math.end = { node: text, delim: '', n: 0 };
                doc.math.push(math);
              });
            }, '', false],
            insertedScript: [200, () => {
              document.querySelectorAll('mjx-container').forEach(node => {
                let target = node.parentNode;
                if (target.nodeName.toLowerCase() === 'li') {
                  target.parentNode.classList.add('has-jax');
                }
              });
            }, '', false]
          }
        }
      };
    </script>

    <script async src="https://cdn.staticfile.org/mathjax/3.0.5/es5/tex-svg.js" ></script>

  













  

  

  

  

  

  





<script src="/binblog/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"model":{"jsonPath":"/binblog/live2dw/assets/koharu.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
